<template>
  <div id="bills_v2">
    <nav aria-label="breadcrumb" role="navigation">
      <ol class="breadcrumb pb-0">
        <li class="breadcrumb-item active ms-2" aria-current="page">
          账单 - 列表
        </li>

        <li class="breadcrumb-item ms-auto">
          <router-link to="/bills/unreviewed">待审核</router-link>
        </li>
        <li class="breadcrumb-item">
          <router-link to="/bills/toSettle">待结算</router-link>
        </li>
        <li class="breadcrumb-item">
          <router-link to="/ent/settlements">结算单</router-link>
        </li>
        <li class="breadcrumb-item me-2">
          <router-link to="/ent/receipts">收款单</router-link>
        </li>
      </ol>
    </nav>

    <div class="card bg-transparent mb-1">
      <div class="card-body px-1 py-1">
        <div class="row mb-1">
          <div class="col-1">
            <select class="form-select col-1" v-model.number="billType">
              <option value="-1">账单类型</option>
              <option value="0">机票</option>
              <option value="5">退票</option>
              <option value="7">改签</option>
              <option value="6">服务</option>
              <option value="2">酒店</option>
              <option value="3">火车票</option>
              <option value="4">租车</option>
            </select>
          </div>
          <div class="col-1">
            <select class="form-select col-1" v-model.number="intlTicket">
              <option value="-1">类型</option>
              <option value="0">国内</option>
              <option value="1">国际</option>
            </select>
          </div>
          <div class="col-1">
            <select class="form-select col-1" v-model.number="payType">
              <option value="0">收款方式</option>
              <option value="1">现金</option>
              <option value="2">信用卡</option>
              <option value="4">支票</option>
              <option value="8">记账</option>
            </select>
          </div>
          <div class="col-1">
            <select class="form-select col-1" v-model.number="reviewed">
              <option value="-1">审核状态</option>
              <option value="0">未审核</option>
              <option value="1">已审核</option>
            </select>
          </div>
          <div class="col-1">
            <select class="form-select col-1" v-model.number="bePaid">
              <option value="-1">收款状态</option>
              <option value="0">未收</option>
              <option value="1">已收</option>
            </select>
          </div>
          <div class="col-1">
            <select class="form-select" v-model.number="paymentStatus">
              <option value="-1">付款状态</option>
              <option value="0">未付</option>
              <option value="1">已付</option>
            </select>
          </div>
          <div class="col-1 px-0">
            <my-select-customer
              :customerId.sync="customerId"
              :enterpriseType="1"
            ></my-select-customer>
          </div>
          <div class="col-1 px-0">
            <my-select-supplier
              :supplierId.sync="supplierId"
            ></my-select-supplier>
          </div>
          <div class="col-1">
            <my-date-picker
              id="date0"
              v-model="beginDate"
              placeholder="账单日期从"
            ></my-date-picker>
          </div>
          <div class="col-1">
            <my-date-picker
              id="date1"
              v-model="endDate"
              placeholder="账单日期到"
            ></my-date-picker>
          </div>
          <div class="col-1">
            <my-date-picker
              id="date2"
              v-model="etdzDateBegin"
              placeholder="出票日期从"
            ></my-date-picker>
          </div>
          <div class="col-1">
            <my-date-picker
              id="date3"
              v-model="etdzDateEnd"
              placeholder="出票日期到"
            ></my-date-picker>
          </div>
        </div>
        <div class="row mb-1">
          <div class="col-1">
            <my-date-picker
              id="date4"
              v-model="auditDateBegin"
              placeholder="审核日期从"
            ></my-date-picker>
          </div>
          <div class="col-1">
            <my-date-picker
              id="date5"
              v-model="auditDateEnd"
              placeholder="审核日期到"
            ></my-date-picker>
          </div>
          <div class="col-1">
            <my-date-picker
              id="date6"
              v-model="settleDateBegin"
              placeholder="结算日期从"
            ></my-date-picker>
          </div>
          <div class="col-1">
            <my-date-picker
              id="date7"
              v-model="settleDateEnd"
              placeholder="结算日期到"
            ></my-date-picker>
          </div>

          <div class="col-1">
            <input
              type="textfield"
              class="form-control"
              size="10"
              placeholder="结算单号"
              v-model.trim="settlementNo"
            />
          </div>
          <div class="col-1">
            <input
              type="textfield"
              class="form-control"
              size="10"
              placeholder="账单备注"
              v-model.trim="remark"
            />
          </div>
          <div class="col-1">
            <input
              type="textfield"
              class="form-control"
              size="10"
              placeholder="成本中心"
              v-model.trim="costCenter"
            />
          </div>
          <div class="col-1">
            <select class="form-select" v-model.number="sc.pageSize">
              <option value="2">2</option>
              <option value="5">5</option>
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="25">25</option>
              <option value="30">30</option>
              <option value="50">50</option>
              <option value="100">100</option>
              <option value="200">200</option>
              <option value="500">500</option>
              <option value="5000">5000</option>
            </select>
          </div>
          <div class="col-1">
            <select class="form-select" v-model.number="orderBy">
              <option value="0">默认</option>
              <option value="3">时间降序</option>
            </select>
          </div>
        </div>
        <div class="row mb-1">
          <div class="col-1">
            <input
              type="textfield"
              class="form-control"
              size="20"
              placeholder="客户名称(编号)模糊查找"
              v-model.trim="likeCustomerName"
            />
          </div>
          <div class="col-1" v-if="billType === 0">
            <input
              type="textfield"
              class="form-control"
              size="15"
              placeholder="旅客姓名模糊查找"
              v-model.trim="likePsgName"
            />
          </div>

          <div class="col-1">
            <input
              type="textfield"
              class="form-control"
              size="10"
              placeholder="账单号"
              v-model.trim="billNum"
            />
          </div>
          <div class="col-2">
            <input
              type="textfield"
              class="form-control"
              size="10"
              placeholder="订单号"
              v-model.trim="orderNo"
            />
            <span class="">查询多个订单号时用逗号或空格隔开</span>
          </div>
          <div class="col">
            <label class="form-check-label">
              <input
                type="checkbox"
                class="form-check-input"
                v-model="blnKeepResult"
              />
              保留查找结果
            </label>
            <button
              type="button"
              class="btn btn-primary ms-2"
              @click.stop="searchBills()"
            >
              查找
            </button>

            <button
              type="button"
              class="btn btn-secondary btn-sm ms-3"
              @click.stop="reset()"
            >
              重置条件
            </button>

            <button
              type="button"
              class="btn btn-secondary btn-sm ms-3"
              @click.stop="emptyResults()"
            >
              清空结果
            </button>

            <div class="col float-end ms-2">
              <router-link to="/setting/bill-templates">下载模板</router-link>
            </div>
            <div class="col float-end ms-2">
              <select class="form-select" v-model.number="downloadFormat">
                <option value="0">默认格式</option>
                <option value="1">格式一</option>
                <template v-for="info in templates">
                  <option
                    :value="info.templateNo"
                    :key="`template_id_` + info.id"
                  >
                    {{ info.name }}
                  </option>
                </template>
              </select>
            </div>
            <div class="col float-end">
              <a
                class="btn btn-success ms-auto"
                @click.stop="downloadBillInfo()"
                href="#"
                >下载</a
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <nav id="pagination-box-1" class="float-end" v-if="orders.length > 10">
      <my-pagination
        name="pagination"
        :row-count="sc.rowCount"
        :page-total="sc.pageTotal"
        :page-no="sc.pageNo"
        @next-page="nextPage"
        @prev-page="prevPage"
        @direct-page="directPage"
      ></my-pagination>
    </nav>

    <table class="table table-striped table-hover table-sm">
      <thead>
        <tr>
          <th>类别</th>
          <th>账单号</th>
          <th>账单日期</th>
          <th>订单号</th>
          <th>客户</th>
          <th>代码/成本/项目</th>
          <th>供应商</th>
          <th>审核日期</th>
          <th>结算</th>
          <th>收支</th>
          <th class="text-end">金额</th>
          <th class="text-end">成本</th>
          <th class="text-end">利润</th>
          <th></th>
          <th></th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-if="orders.length > 10">
          <td colspan="10" class="text-end">当前合计：</td>
          <td class="text-end">{{ totalAmount }}</td>
          <td class="text-end">{{ totalCost }}</td>
          <td class="text-end">{{ totalProfit }}</td>
          <td colspan="3"></td>
        </tr>
        <template v-for="info in orders">
          <tr :key="info.id">
            <td>
              {{ showBillTypeDesc(info.billType) }}
              <span v-if="info.intlTicket === 0">(国内)</span>
              <span class="text-danger" v-else-if="info.intlTicket === 1"
                >(国际)</span
              >
            </td>
            <td>
              <input type="checkbox" :value="info.id" v-model="selectedIds" />
              {{ info.billNum }}
            </td>
            <td>{{ info.opDate }}</td>
            <td>{{ info.orderNo }}</td>
            <td>
              <template v-if="info.customerType === 0">散客</template>
              <template v-else-if="info.customer !== null">
                {{ info.customer.vipName }}
              </template>
            </td>
            <td>
              {{ info.customerCode }}/{{ info.costCenter }}/{{
                info.projectName
              }}
            </td>
            <td>
              <span v-if="info.supplier !== null">{{
                info.supplier.name
              }}</span>
            </td>
            <td>
              <template v-if="info.audited === '1' && info.auditDate !== null">
                <span class="small">{{ info.auditDate }}</span>
              </template>
              <template v-else-if="info.audited === '1'">
                <span class="small">已审核</span>
              </template>
              <template v-else>
                <span class="text-danger small">未审核</span>
              </template>
            </td>
            <td>
              <span class="small" v-if="info.settlementNo !== null">
                {{ info.settleDate }} <br />
                {{ info.settlementNo }}
              </span>
              <span class="text-danger small" v-else-if="info.bePaid === '0'"
                >未结算</span
              >
            </td>
            <td>
              <span class="text-danger small" v-if="info.bePaid === '1'"
                >已收 {{ info.receiptNo }} /
              </span>
              <span class="small" v-if="info.paymentStatus === 1">已付</span>
            </td>
            <td class="text-end">{{ info.billSum }}</td>
            <td class="text-end">{{ info.cost }}</td>
            <td class="text-end">{{ info.profit }}</td>

            <td></td>
            <td>
              <template
                v-if="info.audited === '1' && isAdmin && !blnKeepResult"
              >
                <template v-if="info.paymentStatus === 0">
                  <button
                    type="button"
                    class="btn btn-sm btn-warning ms-2"
                    @click.stop="finishPayment(info.id)"
                  >
                    已付
                  </button>
                </template>
              </template>
            </td>
            <td>
              <router-link :to="`/bill/detail/` + info.id">详情</router-link>
            </td>
          </tr>
          <tr :key="info.id + `-memo`" v-if="info.remark">
            <td colspan="15" class="text-end">
              <strong>备注：</strong>{{ info.remark }}
            </td>
            <td></td>
          </tr>
        </template>
        <tr>
          <td colspan="10" class="text-end">当前合计：</td>
          <td class="text-end">{{ totalAmount }}</td>
          <td class="text-end">{{ totalCost }}</td>
          <td class="text-end">{{ totalProfit }}</td>
          <td colspan="3"></td>
        </tr>
        <tr>
          <td></td>
          <td>
            <button
              @click.stop="checkAll()"
              class="btn btn-sm btn-primary ms-1"
            >
              全选
            </button>
            <button
              @click.stop="uncheckAll()"
              class="btn btn-sm btn-secondary ms-1"
            >
              全否
            </button>
          </td>
          <td colspan="12" class="text-end">
            <template v-if="selectedIds.length > 0">
              <button
                type="button"
                class="btn btn-success me-3"
                @click.stop="auditBills()"
              >
                审核通过
              </button>

              <button
                type="button"
                class="btn btn-danger"
                @click.stop="writeOffBills()"
              >
                销账
              </button>
            </template>
          </td>
          <td colspan="3"></td>
        </tr>
      </tbody>
    </table>

    <nav id="pagination-box-2" class="float-end">
      <my-pagination
        name="pagination"
        :row-count="sc.rowCount"
        :page-total="sc.pageTotal"
        :page-no="sc.pageNo"
        @next-page="nextPage"
        @prev-page="prevPage"
        @direct-page="directPage"
      ></my-pagination>
    </nav>

    <my-modal-receipt-create ref="modalReceiptCreate">
      <span slot="title">{{ modalTitle }}</span>
    </my-modal-receipt-create>
  </div>
</template>

<script>
import {
  searchBills,
  getBillTypeDesc,
  reviewBillInfoPassed,
  auditBill,
  writeOffBillsByReceipt,
  writeOffSingleBill,
  finishBillPayment,
  searchDataTemplates,
} from "@/api/bill.js";
import { APP_FLIGHT_PATH } from "@/common/common.js";
import MyPagination from "@/components/my-pagination.vue";
import MyDatePicker from "@/components/my-datepicker.vue";
import MySelectCustomer from "@/components/my-select2-customer.vue";
import MySelectSupplier from "@/components/my-select2-supplier.vue";
import MyModalReceiptCreate from "@/components/modal/my-modal-receipt-create_v2.vue";

export default {
  name: "MyBills",
  components: {
    MyDatePicker,
    MyPagination,
    MySelectCustomer,
    MySelectSupplier,
    MyModalReceiptCreate,
  },
  data() {
    return {
      selectedIds: [],
      orders: [],
      sc: {
        rowCount: 0,
        pageNo: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      beginDate: "",
      endDate: "",
      etdzDateBegin: "",
      etdzDateEnd: "",
      auditDateBegin: "",
      auditDateEnd: "",
      settleDateBegin: "",
      settleDateEnd: "",
      billType: -1,
      payType: 0,
      customerId: -1,
      supplierId: 0,
      billNum: "",
      orderNo: "",
      flightOrderNo: "",
      remark: "",
      costCenter: "",
      settlementNo: "",
      reviewed: -1,
      bePaid: -1,
      paymentStatus: -1,
      intlTicket: -1,
      downloadFormat: 0,
      orderBy: 3,

      templates: [],

      totalAmount: 0,
      totalCost: 0,
      totalProfit: 0,

      likeCustomerName: "",
      likePsgName: "",

      modalTitle: "",

      blnKeepResult: false,
    };
  },
  computed: {
    isAdmin() {
      return this.$store.getters.isAdmin;
    },
  },
  watch: {
    selectedIds: function () {
      this.caclTotal();
    },
  },
  activated: function () {
    if (window.matchMedia("(max-width: 576px)").matches) {
      this.$router.replace("/h5/bills");
    } else {
      // this.searchBills();
      this.searchDataTemplates();
    }
  },
  methods: {
    showLoading: function (loadingText) {
      this.$store.commit("showLoading", {
        loading: true,
        loadingText: loadingText,
      });
    },
    hideLoading: function () {
      this.$store.commit("showLoading", {
        loading: false,
      });
    },
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    searchDataTemplates: function () {
      const params = {
        "sc.pageNo": 1,
        "sc.pageSize": 100,
      };

      searchDataTemplates(params, (jsonResult) => {
        this.templates = jsonResult.dataList;
      });
    },
    searchBills: function () {
      if (this.blnKeepResult === false) {
        this.selectedIds.splice(0);
        this.orders.splice(0);
      }

      const params = {
        "sc.pageNo": this.sc.pageNo,
        "sc.pageSize": this.sc.pageSize,
        "sc.beginDate": this.beginDate,
        "sc.endDate": this.endDate,
        "sc.etdzDateBegin": this.etdzDateBegin,
        "sc.etdzDateEnd": this.etdzDateEnd,
        "sc.auditDateBegin": this.auditDateBegin,
        "sc.auditDateEnd": this.auditDateEnd,
        "sc.settleDateBegin": this.settleDateBegin,
        "sc.settleDateEnd": this.settleDateEnd,
        "sc.billNum": this.billNum,
        "sc.orderNo": this.orderNo,
        "sc.flightOrderNo": this.flightOrderNo,
        "sc.remark": this.remark,
        "sc.costCenter": this.costCenter,
        "sc.settlementNo": this.settlementNo,
        "sc.intlTicket": this.intlTicket,
        "sc.supplierId": this.supplierId,
        "sc.orderBy": this.orderBy,
        reviewed: this.reviewed,
        billType: this.billType,
        customerId: this.customerId,
        payType: this.payType,
        bePaid: this.bePaid,
        paymentStatus: this.paymentStatus,
        likeCustomerName: this.likeCustomerName,
        likePsgName: this.likePsgName,
      };

      this.showLoading("加载中");
      // console.log(this.blnKeepResult);

      searchBills(
        params,
        (jsonResult) => {
          if (this.blnKeepResult === false) {
            this.orders = jsonResult.dataList;
          } else {
            this.appendSearchResults(jsonResult.dataList);
          }

          this.sc = jsonResult.page;
          this.caclTotal();
        },
        () => {
          this.hideLoading();
        }
      );
    },
    appendSearchResults: function (newResults) {
      //将新的结果合并到已有的结果中
      for (const newResult of newResults) {
        let isExisted = false;
        for (const oldResult of this.orders) {
          if (oldResult.id === newResult.id) {
            // console.log(oldResult.id + ' = '  + newResult.id);
            isExisted = true;
            break;
          }
        }
        if (isExisted === false) {
          // console.log(newResult.id);
          // console.log(newResult);
          this.orders.push(newResult);
        }
      }
    },
    auditBills: function () {
      reviewBillInfoPassed(
        {
          total: this.totalAmount,
          billIds: this.selectedIds,
        },
        (v) => this.commonShowMessage(v)
      );
    },
    auditBillDone: function (id) {
      auditBill(id, (v) => {
        if (v.status === "OK") {
          this.showErrMsg("操作成功");
          this.searchBills();
        } else {
          this.showErrMsg("操作失败: " + jsonResult.errmsg);
        }
      });
    },
    writeOffBill: function (id) {
      writeOffSingleBill(id, (v) => {
        if (v.status !== "OK") {
          this.showErrMsg(v.errmsg, "danger");
        } else {
          this.showErrMsg("操作成功");
          this.searchBills();
        }
      });
    },
    writeOffBills: function (id) {
      //校验所选账单是否属于同一个公司
      let customerId = -1;
      let customerName;
      let billsAmount = 0;
      for (const info of this.orders) {
        if (this.selectedIds.indexOf(info.id) >= 0) {
          if (customerId === -1) {
            console.log(info);
            customerId = info.customerId;
            if (customerId === 0) {
              customerName = "散客";
            } else {
              customerName = info.customer.vipName;
            }
          } else if (customerId !== info.customerId) {
            this.showErrMsg("请选择同一客户", "danger");
            return;
          }
          billsAmount += info.billSum;
        }
      }

      this.$refs.modalReceiptCreate
        .modal(customerId, customerName, billsAmount)
        .then((v) => {
          const params = {
            customerId: v.customerId,
            amount: v.amount,
            remark: v.remark,
            receiptBank: v.receiptBank,
            receiptDate: v.receiptDate,
            billIds: this.selectedIds,
          };

          writeOffBillsByReceipt(v.receiptId, params, (v) =>
            this.commonShowMessage(v)
          );
        })
        .catch((ex) => {});
    },
    finishPayment: function (id) {
      //完成支付
      finishBillPayment(id, (v) => {
        if (v.status !== "OK") {
          this.showErrMsg(v.errmsg, "danger");
        } else {
          this.showErrMsg("操作成功");
          this.searchBills();
        }
      });
    },
    showBillTypeDesc: function (val) {
      return getBillTypeDesc(val);
    },
    resetTotal: function () {
      this.totalAmount = 0;
      this.totalCost = 0;
      this.totalProfit = 0;
    },
    caclTotal: function () {
      this.resetTotal();

      for (const info of this.orders) {
        if (this.selectedIds.length > 0) {
          if (this.selectedIds.indexOf(info.id) >= 0) {
            this.totalAmount += info.billSum;
            this.totalCost += info.cost;
            this.totalProfit += info.profit;
          }
        } else {
          this.totalAmount += info.billSum;
          this.totalCost += info.cost;
          this.totalProfit += info.profit;
        }
      }

      this.totalAmount = Math.round(this.totalAmount * 100) / 100;
      this.totalCost = Math.round(this.totalCost * 100) / 100;
      this.totalProfit = Math.round(this.totalProfit * 100) / 100;
    },
    reset: function () {
      this.customerId = -1;
      this.sc.pageNo = 1;
      this.beginDate = "";
      this.endDate = "";
      this.etdzDateBegin = "";
      this.etdzDateEnd = "";
      this.auditDateBegin = "";
      this.auditDateEnd = "";
      this.settleDateBegin = "";
      this.settleDateEnd = "";
      this.billType = -1;
      this.billNum = "";
      this.orderNo = "";
      this.flightOrderNo = "";
      this.remark = "";
      this.costCenter = "";
      this.settlementNo = "";
      this.reviewed = -1;
      this.bePaid = -1;
      this.paymentStatus = -1;
      this.intlTicket = -1;
      this.supplierId = 0;
      this.likeCustomerName = "";
      this.likePsgName = "";
    },
    downloadBillInfo: function () {
      const params =
        "sc.pageNo=" +
        this.sc.pageNo +
        "&sc.beginDate=" +
        this.beginDate +
        "&sc.endDate=" +
        this.endDate +
        "&reviewed=" +
        this.reviewed +
        "&billType=" +
        this.billType +
        "&customerId=" +
        this.customerId +
        "&payType=" +
        this.payType +
        "&bePaid=" +
        this.bePaid +
        "&paymentStatus=" +
        this.paymentStatus +
        "&sc.billNum=" +
        this.billNum +
        "&sc.orderNo=" +
        this.orderNo +
        "&sc.flightOrderNo=" +
        this.flightOrderNo +
        "&sc.remark=" +
        this.remark +
        "&sc.costCenter=" +
        this.costCenter +
        "&sc.settlementNo=" +
        this.settlementNo +
        "&sc.etdzDateBegin=" +
        this.etdzDateBegin +
        "&sc.etdzDateEnd=" +
        this.etdzDateEnd +
        "&sc.auditDateBegin=" +
        this.auditDateBegin +
        "&sc.auditDateEnd=" +
        this.auditDateEnd +
        "&sc.settleDateBegin=" +
        this.settleDateBegin +
        "&sc.settleDateEnd=" +
        this.settleDateEnd +
        "&sc.intlTicket=" +
        this.intlTicket +
        "&sc.supplierId=" +
        this.supplierId +
        "&format=" +
        this.downloadFormat +
        "&likeCustomerName=" +
        this.likeCustomerName +
        "&likePsgName=" +
        this.likePsgName;

      const url = APP_FLIGHT_PATH + "/downloadBillInfo.do?" + params;
      window.open(url);
    },
    commonShowMessage: function (jsonResult) {
      if (jsonResult.status !== "OK") {
        this.showErrMsg("失败：" + jsonResult.errmsg, "danger");
      } else {
        this.searchBills();
        if (jsonResult.desc !== "") {
          this.showErrMsg(jsonResult.desc);
        } else {
          this.showErrMsg("操作成功");
        }
      }
    },
    prevPage: function () {
      this.sc.pageNo = this.sc.pageNo - 1;
      if (this.sc.pageNo < 1) this.sc.pageNo = 1;
      this.searchBills();
    },
    nextPage: function () {
      this.sc.pageNo = this.sc.pageNo + 1;
      this.searchBills();
    },
    directPage: function (pageNo) {
      this.sc.pageNo = pageNo;
      this.searchBills();
    },
    checkAll: function () {
      const self = this;
      this.selectedIds.splice(0);
      this.orders.forEach(function (item) {
        self.selectedIds.push(item.id);
      });
    },
    uncheckAll: function () {
      this.selectedIds.splice(0);
    },
    emptyResults: function () {
      this.selectedIds.splice(0);
      this.orders.splice(0);
    },
  },
};
</script>
